<template>
  <div class="tab-content-container avatar-upload">
    <h3 class="section-title">头像设置</h3>

    <div class="avatar-container">
      <div class="current-avatar">
        <h4>当前头像</h4>
        <el-avatar :size="100" :src="currentAvatar || defaultAvatar" />
      </div>

      <div class="upload-avatar">
        <h4>上传新头像</h4>
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleCustomUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar-preview" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">支持jpg、png格式，文件大小不超过2MB</div>

        <div v-if="imageUrl" class="avatar-actions">
          <el-button type="primary" @click="saveAvatar">使用此头像</el-button>
          <el-button @click="cancelUpload">取消</el-button>
        </div>
      </div>
    </div>

    <div v-if="!imageUrl" class="default-avatars">
      <h4>选择默认头像</h4>
      <div v-loading="loadingAvatars" class="default-avatar-list">
        <div
          v-for="(avatar, index) in defaultAvatars"
          :key="index"
          class="default-avatar-item"
          :class="{ selected: selectedDefaultAvatar === avatar }"
          @click="selectDefaultAvatar(avatar)"
        >
          <el-avatar :size="60" :src="avatar" />
        </div>
      </div>
      <el-button
        type="primary"
        @click="useDefaultAvatar"
        :disabled="!selectedDefaultAvatar || loadingAvatars"
      >
        使用选中头像
      </el-button>
    </div>

    <!-- 添加一个临时的调试按钮 -->
    <div
      class="debug-section"
      style="margin-top: 20px; border-top: 1px dashed #ccc; padding-top: 10px"
    >
      <el-button @click="debugRefreshAvatar">调试: 刷新头像显示</el-button>
      <p style="font-size: 12px; color: #999">
        当前头像URL: {{ currentAvatar || "(无)" }}
      </p>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import api from "@/utils/api";

export default {
  name: "AvatarUpload",
  components: {
    Plus,
  },
  props: {
    userInfo: {
      type: Object,
      required: true,
    },
  },
  emits: ["update-avatar"],
  setup(props, { emit }) {
    const currentAvatar = ref("");
    const defaultAvatar = ref(
      "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"
    );
    const imageUrl = ref("");
    const uploadLoading = ref(false);
    const defaultAvatars = ref([]);
    const loadingAvatars = ref(false);
    const selectedDefaultAvatar = ref("");

    // 使用和UserCenter相同的接口获取用户头像
    const fetchUserProfile = async () => {
      try {
        const response = await api.get("/user/profile");
        if (response.data.code === 200) {
          const userData = response.data.data;
          // 设置头像，确保不为undefined
          currentAvatar.value = userData.avatar || "";
          console.log("直接从API获取的头像:", currentAvatar.value);
        } else {
          console.warn("获取用户资料失败，尝试使用props中的头像");
          currentAvatar.value = props.userInfo?.avatar || "";
        }
      } catch (error) {
        console.error("获取用户资料失败:", error);
        currentAvatar.value = props.userInfo?.avatar || "";
      }
    };

    onMounted(() => {
      // 组件挂载时立即获取用户资料
      fetchUserProfile();
      // 获取默认头像列表
      fetchDefaultAvatars();
    });

    const fetchDefaultAvatars = async () => {
      loadingAvatars.value = true;
      try {
        const response = await api.get("/user/avatar/defaults");
        if (response.data.code === 200) {
          defaultAvatars.value = response.data.data;
        } else {
          ElMessage.error(response.data.message || "获取默认头像列表失败");
          // 加载失败时使用备用头像
          setFallbackAvatars();
        }
      } catch (error) {
        console.error("获取默认头像列表失败:", error);
        ElMessage.error("获取默认头像列表失败，使用备用头像");
        // 加载失败时使用备用头像
        setFallbackAvatars();
      } finally {
        loadingAvatars.value = false;
      }
    };

    // 设置备用头像（当API调用失败时使用）
    const setFallbackAvatars = () => {
      defaultAvatars.value = [
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
        "https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png",
      ];
    };

    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        ElMessage.error("头像只能是JPG或PNG格式!");
        return false;
      }

      if (!isLt2M) {
        ElMessage.error("头像大小不能超过2MB!");
        return false;
      }

      return true;
    };

    const handleCustomUpload = async (options) => {
      const { file } = options;
      uploadLoading.value = true;

      try {
        // 创建FormData对象
        const formData = new FormData();
        formData.append("avatar", file);

        // 调用上传接口
        const response = await api.post("/user/avatar/upload", formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        });

        if (response.data.code === 200) {
          imageUrl.value = response.data.data.url;
          ElMessage.success('图片上传成功，请点击"使用此头像"保存');
        } else {
          ElMessage.error(response.data.message || "上传失败");
        }
      } catch (error) {
        console.error("上传头像失败:", error);
        ElMessage.error("上传失败，请稍后再试");
      } finally {
        uploadLoading.value = false;
      }
    };

    const saveAvatar = async () => {
      if (!imageUrl.value) {
        ElMessage.warning("请先上传头像");
        return;
      }

      uploadLoading.value = true;

      try {
        const response = await api.put("/user/avatar", {
          avatarUrl: imageUrl.value,
        });

        if (response.data.code === 200) {
          // 保存新头像到本地存储
          try {
            const storedUserInfo = JSON.parse(
              localStorage.getItem("userInfo") || "{}"
            );
            storedUserInfo.avatar = imageUrl.value;
            localStorage.setItem("userInfo", JSON.stringify(storedUserInfo));
          } catch (e) {
            console.error("保存头像到本地存储失败", e);
          }

          // 更新当前组件显示
          currentAvatar.value = imageUrl.value;

          // 发送事件到父组件
          emit("update-avatar", { avatar: imageUrl.value });

          // 直接触发全局事件
          const event = new CustomEvent("userAvatarUpdated", {
            detail: { avatar: imageUrl.value },
          });
          window.dispatchEvent(event);

          ElMessage.success("头像更新成功");
          imageUrl.value = "";

          // 强制刷新页面数据
          window.dispatchEvent(new CustomEvent("forceRefreshUserData"));
        } else {
          ElMessage.error(response.data.message || "设置头像失败");
        }
      } catch (error) {
        console.error("设置头像失败:", error);
        ElMessage.error("设置头像失败，请稍后再试");
      } finally {
        uploadLoading.value = false;
      }
    };

    const cancelUpload = () => {
      imageUrl.value = "";
    };

    const selectDefaultAvatar = (avatar) => {
      selectedDefaultAvatar.value = avatar;
    };

    const useDefaultAvatar = async () => {
      if (!selectedDefaultAvatar.value) {
        ElMessage.warning("请先选择一个默认头像");
        return;
      }

      uploadLoading.value = true;

      try {
        const response = await api.put("/user/avatar", {
          avatarUrl: selectedDefaultAvatar.value,
        });

        if (response.data.code === 200) {
          // 保存新头像到本地存储
          try {
            const storedUserInfo = JSON.parse(
              localStorage.getItem("userInfo") || "{}"
            );
            storedUserInfo.avatar = selectedDefaultAvatar.value;
            localStorage.setItem("userInfo", JSON.stringify(storedUserInfo));
          } catch (e) {
            console.error("保存头像到本地存储失败", e);
          }

          // 更新当前组件显示
          currentAvatar.value = selectedDefaultAvatar.value;

          // 发送事件到父组件
          emit("update-avatar", { avatar: selectedDefaultAvatar.value });

          // 直接触发全局事件
          const event = new CustomEvent("userAvatarUpdated", {
            detail: { avatar: selectedDefaultAvatar.value },
          });
          window.dispatchEvent(event);

          ElMessage.success("头像更新成功");

          // 重新获取用户资料（可选，用于确保数据同步）
          setTimeout(() => {
            fetchUserProfile();
          }, 500);

          // 清空选中的默认头像
          selectedDefaultAvatar.value = "";
        } else {
          ElMessage.error(response.data.message || "设置头像失败");
        }
      } catch (error) {
        console.error("设置头像失败:", error);
        ElMessage.error("设置头像失败，请稍后再试");
      } finally {
        uploadLoading.value = false;
      }
    };

    // 添加调试方法
    const debugRefreshAvatar = () => {
      console.log("调试: 刷新头像");
      console.log("当前头像URL:", currentAvatar.value);
      console.log("用户信息中的头像:", props.userInfo?.avatar);

      // 强制触发事件
      const avatar = currentAvatar.value || props.userInfo?.avatar;
      if (avatar) {
        const event = new CustomEvent("userAvatarUpdated", {
          detail: { avatar: avatar },
        });
        window.dispatchEvent(event);
        console.log("已触发头像更新事件");
      }

      // 重新获取用户资料
      fetchUserProfile();
    };

    return {
      currentAvatar,
      defaultAvatar,
      imageUrl,
      uploadLoading,
      defaultAvatars,
      loadingAvatars,
      selectedDefaultAvatar,
      beforeAvatarUpload,
      handleCustomUpload,
      cancelUpload,
      saveAvatar,
      selectDefaultAvatar,
      useDefaultAvatar,
      debugRefreshAvatar,
    };
  },
};
</script>

<style scoped>
.avatar-upload {
  width: 800px !important; /* 固定宽度 */
}

.section-title {
  width: 100%;
  margin-top: 0;
  margin-bottom: 20px;
  color: var(--text-primary);
  font-size: 18px;
  border-bottom: 1px solid var(--border-color);
  padding-bottom: 10px;
}

.avatar-container {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 50px;
}

.current-avatar,
.upload-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.current-avatar h4,
.upload-avatar h4 {
  margin-bottom: 15px;
  color: var(--text-primary);
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  border: 1px dashed var(--border-color);
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: var(--primary-color);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-tip {
  margin-top: 10px;
  font-size: 12px;
  color: var(--text-secondary);
  text-align: center;
}

.avatar-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 15px;
}

.default-avatars {
  margin-bottom: 30px;
}

.default-avatar-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.default-avatar-item {
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.default-avatar-item:hover {
  background-color: #f5f7fa;
}

.default-avatar-item.selected {
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
}
</style> 